# -*- coding: binary -*-

module Msf::Exploit::Remote::HTTP::Gitea::Version
  # Powered by Gitea Version
  GITEA_VERSION_PATTERN = 'Gitea Version: (?<version>[\da-zA-Z.]+)'.freeze

  # Extracts the Gitea version information from base path
  #
  # @param res [Rex::Proto::Http::Response] Rex HTTP Response object
  # @return [String,nil] gitea version if found, nil otherwise
  def gitea_version(res = nil)
    # detect version from /
    version = gitea_version_helper(
      normalize_uri(target_uri.path),
      /#{GITEA_VERSION_PATTERN}/,
      res
    )
    return version
  end

  def gitea_version_helper(url, regex, res)
    res ||= send_request_cgi({
      'method' => 'GET',
      'uri' => url,
      'keep_cookies' => true
    })
    if res
      match = res.body.match(regex)
      return match[1] if match
    end

    nil
  end
end
